// recipeDetail.js
const app = getApp(); // 添加获取app实例

Page({
  data: {
    recipeId: null,
    recipe: null,
    activeTab: 0, // 0: 材料, 1: 步骤
    checkedItems: {},
    timer: {
      isRunning: false,
      startTime: 0,
      elapsedTime: 0,
      displayTime: '00:00:00'
    }
  },

  onLoad: function(options) {
    const { id } = options;
    this.setData({ recipeId: id });
    this.loadRecipeDetail(id);
  },

  onShow: function() {
    // 页面显示时重新加载数据，以便获取编辑后的内容
    if (this.data.recipeId) {
      this.loadRecipeDetail(this.data.recipeId);
    }
  },

  loadRecipeDetail(id) {
    try {
      // 从全局数据中获取配方数据
      const allRecipes = app.globalData.recipes || [];
      const recipe = allRecipes.find(r => r.id.toString() === id.toString());
      
      if (recipe) {
        // 打印详细数据以便调试
        console.log('加载配方成功:', recipe);
        if (recipe.mainIngredients && recipe.mainIngredients.length > 0) {
          console.log('主料数据样例:', {
            第一项: recipe.mainIngredients[0],
            类型: typeof recipe.mainIngredients[0].amount,
            包含g或ml: recipe.mainIngredients[0].amount.includes && 
                    (recipe.mainIngredients[0].amount.includes('g') || 
                     recipe.mainIngredients[0].amount.includes('ml'))
          });
          
          // 处理主料数据，确保单位显示正确
          const processedMainIngredients = recipe.mainIngredients.map(item => {
            // 如果amount是纯数字，默认添加'g'单位
            if (typeof item.amount === 'number' || !isNaN(item.amount)) {
              return {
                ...item,
                displayAmount: item.amount,
                displayUnit: item.unit || 'g'
              };
            } else if (typeof item.amount === 'string') {
              // 如果amount是字符串且已经包含单位，则直接使用
              return {
                ...item,
                displayAmount: item.amount,
                displayUnit: ''
              };
            } else {
              return {
                ...item,
                displayAmount: item.amount || '',
                displayUnit: item.unit || ''
              };
            }
          });
          
          // 更新数据结构
          recipe.mainIngredients = processedMainIngredients;
        }

        // 处理步骤材料，确保显示正确
        if (recipe.steps && recipe.steps.length > 0) {
          recipe.steps.forEach(step => {
            if (step.materials && step.materials.length > 0) {
              step.materials.forEach(material => {
                // 如果没有amount，设置为空字符串，避免undefined显示
                if (!material.amount && material.amount !== 0) {
                  material.amount = '';
                }
                
                // 如果amount不是字符串，转换为字符串
                if (typeof material.amount !== 'string') {
                  material.amount = String(material.amount);
                }
                
                // 如果有单位且amount中不包含单位，则显示单位
                if (material.unit && !material.amount.includes(material.unit)) {
                  material.amount = `${material.amount}${material.unit}`;
                }
              });
            }
          });
        }
        
        this.setData({ recipe });
      } else {
        // 如果找不到配方，显示默认数据
        const mockRecipe = {
          id: 101,
          name: '提拉米苏',
          category: '甜点',
          difficulty: '中等',
          time: '45分钟',
          mainIngredients: [
            { name: '马斯卡彭奶酪', amount: '250g' },
            { name: '手指饼干', amount: '150g' },
            { name: '咖啡', amount: '150ml' },
            { name: '蛋黄', amount: '4个' }
          ],
          additionalIngredients: [
            { name: '白砂糖', amount: '60g' },
            { name: '可可粉', amount: '10g' }
          ],
          steps: [
            { 
              desc: '准备一杯浓缩咖啡，加入少量朗姆酒（可选），放凉备用', 
              time: '5分钟',
              materials: [
                { name: '咖啡', amount: '150ml' },
                { name: '朗姆酒', amount: '10ml' }
              ]
            },
            { 
              desc: '分离蛋黄和蛋白，蛋黄中加入三分之一的糖，搅拌至糖溶解，颜色变浅', 
              time: '5分钟',
              materials: [
                { name: '蛋黄', amount: '4个' },
                { name: '白砂糖', amount: '20g' }
              ],
              result: '蛋黄糖混合物',
              resultName: '蛋黄糊'
            },
            { 
              desc: '加入马斯卡彭奶酪，搅拌均匀成奶酪糊', 
              time: '3分钟',
              materials: [
                { name: '马斯卡彭奶酪', amount: '250g' },
                { name: '蛋黄糊', amount: '全部' }
              ],
              result: '奶酪和蛋黄的混合物',
              resultName: '奶酪糊'
            },
            { 
              desc: '将手指饼干浸入咖啡中，时间控制在1-2秒', 
              time: '2分钟',
              materials: [
                { name: '手指饼干', amount: '150g' },
                { name: '咖啡', amount: '150ml' }
              ]
            },
            { 
              desc: '在容器底部铺一层浸泡过咖啡的手指饼干', 
              time: '3分钟' 
            },
            { 
              desc: '在饼干上均匀抹上一层奶酪糊', 
              time: '5分钟',
              materials: [
                { name: '奶酪糊', amount: '一半' }
              ]
            },
            { 
              desc: '重复上述步骤，直到材料用完', 
              time: '10分钟' 
            },
            { 
              desc: '在最上层撒上可可粉', 
              time: '2分钟',
              materials: [
                { name: '可可粉', amount: '10g' }
              ]
            },
            { 
              desc: '放入冰箱冷藏至少4小时，最好隔夜', 
              time: '4小时',
              result: '成品提拉米苏',
              resultName: '提拉米苏'
            }
          ],
          tips: '1. 手指饼干不要浸泡太久，以免过软影响口感\n2. 可可粉最好在食用前撒，保持表面干爽\n3. 冷藏时间越长，风味越好',
          imageUrl: ''
        };
      
        this.setData({ recipe: mockRecipe });
        console.log('未找到配方，使用默认数据');
      }
    } catch (error) {
      console.error('加载配方失败:', error);
      wx.showToast({
        title: '加载配方失败',
        icon: 'none'
      });
    }
  },

  switchTab(e) {
    const tab = e.currentTarget.dataset.tab;
    this.setData({ activeTab: tab });
  },

  toggleCheckItem(e) {
    const { index } = e.currentTarget.dataset;
    const checkedItems = { ...this.data.checkedItems };
    
    if (checkedItems[index]) {
      delete checkedItems[index];
    } else {
      checkedItems[index] = true;
    }
    
    this.setData({ checkedItems });
  },

  startTimer() {
    if (this.data.timer.isRunning) return;
    
    const startTime = Date.now() - (this.data.timer.elapsedTime || 0);
    this.setData({
      timer: {
        ...this.data.timer,
        isRunning: true,
        startTime
      }
    });
    
    this.timerInterval = setInterval(() => {
      const elapsedTime = Date.now() - this.data.timer.startTime;
      const seconds = Math.floor((elapsedTime / 1000) % 60);
      const minutes = Math.floor((elapsedTime / (1000 * 60)) % 60);
      const hours = Math.floor(elapsedTime / (1000 * 60 * 60));
      
      const displayTime = `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
      
      this.setData({
        timer: {
          ...this.data.timer,
          elapsedTime,
          displayTime
        }
      });
    }, 1000);
  },

  pauseTimer() {
    if (!this.data.timer.isRunning) return;
    
    clearInterval(this.timerInterval);
    this.setData({
      timer: {
        ...this.data.timer,
        isRunning: false
      }
    });
  },

  resetTimer() {
    clearInterval(this.timerInterval);
    this.setData({
      timer: {
        isRunning: false,
        startTime: 0,
        elapsedTime: 0,
        displayTime: '00:00:00'
      }
    });
  },

  deleteStep(e) {
    const { index } = e.currentTarget.dataset;
    const recipe = this.data.recipe;
    
    // 如果只有一个步骤，不允许删除
    if (recipe.steps.length <= 1) {
      wx.showToast({
        title: '至少需保留一个步骤',
        icon: 'none'
      });
      return;
    }
    
    wx.showModal({
      title: '确认删除',
      content: `确定要删除步骤 ${index + 1} 吗？`,
      confirmColor: '#ff4444',
      success: (res) => {
        if (res.confirm) {
          // 复制一份步骤数组
          const updatedSteps = [...recipe.steps];
          // 删除指定索引的步骤
          updatedSteps.splice(index, 1);
          
          // 更新本地数据
          const updatedRecipe = {
            ...recipe,
            steps: updatedSteps
          };
          
          // 更新视图
          this.setData({
            recipe: updatedRecipe
          });
          
          // 更新全局数据
          this.updateRecipeInGlobal(updatedRecipe);
          
          wx.showToast({
            title: '步骤已删除',
            icon: 'success'
          });
        }
      }
    });
  },
  
  updateRecipeInGlobal(updatedRecipe) {
    try {
      const allRecipes = app.globalData.recipes || [];
      const recipeIndex = allRecipes.findIndex(r => r.id.toString() === this.data.recipeId.toString());
      
      if (recipeIndex !== -1) {
        // 更新全局数据中的配方
        app.globalData.recipes[recipeIndex] = updatedRecipe;
        
        // 保存到本地存储
        app.saveLocalData();
        console.log('配方更新成功:', updatedRecipe);
      } else {
        console.error('未找到要更新的配方');
      }
    } catch (error) {
      console.error('更新配方失败:', error);
      wx.showToast({
        title: '更新配方失败',
        icon: 'none'
      });
    }
  },

  editRecipe() {
    wx.navigateTo({
      url: `/pages/recipeEdit/recipeEdit?id=${this.data.recipeId}`
    });
  },

  onShareAppMessage() {
    return {
      title: `${this.data.recipe.name} - 配方分享`,
      path: `/pages/recipeDetail/recipeDetail?id=${this.data.recipeId}`
    };
  },

  onUnload: function() {
    if (this.timerInterval) {
      clearInterval(this.timerInterval);
    }
  }
}); 